package com.mini.config;

import com.alibaba.fastjson.JSON;
import com.mini.vo.BusinessResult;
import com.mini.vo.CommonResultMessage;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理
 *
 * @author zl
 * @version 1.0
 * @date Created in 2020/2/27
 */
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {


    private Logger logger = LoggerFactory.getLogger(this.getClass());


    /**
     * 未登录
     *
     * @param exception
     * @return
     */
    @ExceptionHandler({UnLoginException.class})
    public ResponseEntity<Object> handleParamException(UnLoginException exception) {
        logger.error("【handleParamException】：" + exception.getMessage());
        BusinessResult businessResult = BusinessResult.createInstance(Long.valueOf(HttpStatus.UNAUTHORIZED.value()), exception.getMessage(),null);
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(businessResult);
    }

    /**
     * 异常处理
     *
     * @param exception
     * @return
     */
    @ExceptionHandler({Exception.class})
    public ResponseEntity<Object> handleBusinessException(Exception exception) {
        logger.error("【handleException】：{} ,ex = {}" , exception.getMessage() ,exception);
        BusinessResult businessResult = BusinessResult.createInstance(Long.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()), exception.getMessage(),null);
        return ResponseEntity.status(HttpStatus.OK).body(businessResult);
    }

    /**
     * 业务异常处理
     *
     * @param ce
     * @return
     */
    @ExceptionHandler({BusinessException.class})
    public ResponseEntity<Object> handleBusinessException(BusinessException ce, HttpServletRequest request) {
        String method = request.getMethod();
        String uri = request.getRequestURI();

        Map<String, String> heads = getHeaders(request);
        Map<String, String> params = getHeaders(request);

        logger.error("API:handleBusinessException excepiton={} cause={} method={} uri={} heads={} paramInfo={}", ce.getClass().getSimpleName(), ce.getMessage(), method, uri, JSON.toJSONString(heads), JSON.toJSONString(params));

        BusinessResult businessResult = BusinessResult.createInstance(CommonResultMessage.ERROR, ce.getMessage());
        return ResponseEntity.status(HttpStatus.OK).body(businessResult);
    }

    private Map<String, String> getHeaders(HttpServletRequest request){

        Map<String, String> heads = new HashMap<>(10);
        Enumeration<String> headNames = request.getHeaderNames();
        while (headNames.hasMoreElements()) {
            String name = headNames.nextElement();
            String value = request.getParameter(name);
            if (StringUtils.isNotBlank(value)) {
                heads.put(name, value);
            }
        }
        return heads;
    }

    private Map<String, String> getParams(HttpServletRequest request){
        Map<String, String> params = new HashMap<>(10);
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String name = parameterNames.nextElement();
            String value = request.getParameter(name);
            if (StringUtils.isNotBlank(value)) {
                params.put(name, value);
            }
        }
        return params;
    }

}
